package com.logistics.utils.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.logistics.utils.tool.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void set(String key, Object object, Long time){
        if(object instanceof String){
            setString(key, object);
        }
        if(object instanceof Set){
            setSet(key, object);
        }
        if(StringUtils.isNotNull(time)){
            stringRedisTemplate.expire(key, time, TimeUnit.MINUTES);
        }
    }

    public void setString(String key, Object object){
        if(object instanceof String){
            String value = (String) object;
            stringRedisTemplate.opsForValue().set(key, value);
        }
    }


    public void setSet(String key, Object object){
        Set<String> valueSet = (Set<String>) object;
        for(String string : valueSet){
            stringRedisTemplate.opsForSet().add(key, string);
        }
    }

    public String getString(String key){
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * hash取值
     * @param key
     * @return
     */
    public Object getObject(String key){
        return stringRedisTemplate.boundHashOps(key).values();
    }

    public void deleteKey(String key){
        stringRedisTemplate.delete(key);
    }

    public JSONObject hgetAll(String key) {
        Map<Object, Object> obj = stringRedisTemplate.opsForHash().entries(key);
        if (obj.size() == 0) {
            return null;
        }
        return JSON.parseObject(JSON.toJSONString(obj));
    }

    public String hget(String key, String field) {
        Object obj = stringRedisTemplate.opsForHash().get(key, field);
        if (obj != null) {
            return obj.toString();
        }
        return null;
    }

    public void hset(String key, String field, String value) {
        stringRedisTemplate.opsForHash().put(key, field, value);
    }

    public void hdel(String key, String field) {
        stringRedisTemplate.opsForHash().delete(key, field);
    }

    public void hsetAll(String key, Map<String, String> valueMap) {
        stringRedisTemplate.opsForHash().putAll(key, valueMap);
    }

    public boolean hexist(String key, String field) {
        return stringRedisTemplate.opsForHash().hasKey(key, field);
    }

    public boolean hExist(String key, String field) {
        return stringRedisTemplate.opsForHash().hasKey(key, field);
    }
}
